package com.linzm.leetcode.primary.数组.移除元素;

import org.junit.Test;

import java.util.Arrays;

/**
 * @Author zimingl
 * @Date 2022/10/6 16:44
 * @Description: TODO
 */
public class 数组977有序数组的平方 {

    public int[] sortedSquares(int[] nums) {
        int[] ans = new int[nums.length];
        for (int i = 0; i < nums.length; ++i) {
            ans[i] = nums[i] * nums[i];
        }
        Arrays.sort(ans);
        return ans;
    }

    public int[] sortedSquares2(int[] nums) {
        int[] ans = new int[nums.length];
        int index = nums.length-1;
        int left = 0;
        int right = nums.length-1;
        while (left<=right){
            if (nums[left]*nums[left] >= nums[right]*nums[right]){
                ans[index--] = nums[left]*nums[left];
                left++;
            } else {
                ans[index--] = nums[right]*nums[right];
                right--;
            }
        }
        return ans;
    }

    private int[] sortedStatements3(int[] nums){
        int[] newNums = new int[nums.length];
        int length = nums.length;
        for (int i = 0, k = 0, j = length - 1; i <= j; ) {
            if (nums[i]*nums[i] <= nums[j]*nums[j]){
                newNums[k++] = nums[i]*nums[i];
                i ++;
            } else {
                newNums[k++] = nums[j] * nums[j];
                j --;
            }
        }
        return newNums;
    }


    @Test
    public void test(){
        int[] nums = new int[]{-4,-1,0,3,10};
        sortedSquares(nums);
    }

}
